﻿using JustMetClient.Commons;
using Azylee.Core.DataUtils.CollectionUtils;
using Azylee.Core.DataUtils.StringUtils;
using Azylee.Core.IOUtils.DirUtils;
using Azylee.Core.IOUtils.TxtUtils;
using Azylee.Core.Plus.DataUtils.JsonUtils;
using Azylee.Core.ProcessUtils;
using Azylee.Core.VersionUtils;
using Azylee.Update.UpdateUtils;
using Azylee.YeahWeb.FTPUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace JustMetClient.Modules.UpdateModule
{
    public static class UpdateHelper
    {
        public static bool CheckNewVersion()
        {
            string errorString = IniTool.GetString(R.Files.Settings, "Update", "Error", "");
            //如果更新错误字符串不为空
            if (!string.IsNullOrWhiteSpace(errorString))
            {
                string current = DateTime.Now.ToString("yyyyMMddHH");
                List<string> errList = errorString.Split('|').ToList();

                //如果错误一小时内错误次数出现3次及以上，则停止更新检查
                if (errList.Count(x => x.Contains(current)) >= 3)
                {
                    R.Log.v("最近一小时内，更新失败次数已达3次，为保证客户端计算机稳定，当前时刻暂停更新功能");
                    return false;
                }
            }

            //监测新版本
            AppUpdateTool aut = new AppUpdateTool();
            FtpTool ftpTool = new FtpTool(R.Config.FTP_IP, R.Config.FTP_ACCOUNT, R.Config.FTP_PASSWORD);
            bool flag = ftpTool.Download(R.Config.ASVersionPath + R.Config.ASVersionFile, DirTool.Combine(R.Paths.Temp, "JustMetClient.version"));
            if (flag)
            {
                string s = TxtTool.Read(DirTool.Combine(R.Paths.Temp, "JustMetClient.version"));
                AppUpdateInfo info = JsonTool.ToObjFromStr<AppUpdateInfo>(s);
                if (info.Version != R.Version.ToString())
                {
                    //有新版本，标记目标最新版本
                    IniTool.Set(R.Files.Settings, "Version", "JustMetClient-New", info.Version);
                    return true;
                }
            }
            return false;
        }
        public static void Update()
        {
            //AppUpdateTool aut = new AppUpdateTool();
            //AppUpdateInfo info;
            //string file = DirTool.Combine(R.Paths.Temp, "version.txt");

            //if (File.Exists(file))
            //{
            //    string s = TxtTool.Read(file);
            //    int fgGetVersion = aut.GetNewVersionByString(s, R.Version, out info);
            //    if (fgGetVersion >= 0)
            //    {  }
            //}

            R.Log.i("========== 程序启动：JustMetClient.Update（正常启动） ==========");
            //有新版本需要更新，启动更新程序，退出主程序
            ProcessTool.Start(R.Files.Update);
            R.Log.i("========== 程序退出：JustMetClient（更新程序） ==========");
            R.MainUI.ExitApp();
        }
        public static void CleanHistory()
        {
            //获取当前版本
            string current = IniTool.GetString(R.Files.Settings, "Version", "JustMetClient-Current", "");
            //最新更新的版本
            string newVersion = IniTool.GetString(R.Files.Settings, "Version", "JustMetClient-New", current);
            //获取所有执行过的版本
            string history = IniTool.GetString(R.Files.Settings, "Version", "JustMetClient-History", "");
            if (Str.Ok(current) && Str.Ok(history))
            {
                //整理所有版本
                List<string> _temp = history.Split('|').ToList();
                List<string> list = new List<string>();
                if (ListTool.HasElements(_temp))
                {
                    Version _version = null;
                    _temp.ForEach(x => { if (Version.TryParse(x, out _version)) list.Add(x); });
                }

                int persist = 3;
                if (list.Count > persist)
                {
                    #region 开始清理主程序版本
                    for (int i = 0; i < list.Count - persist; i++)
                    {
                        if (!StringTool.IsNullOrWhiteSpace(list[i]) && !list[i].Equals(current) && !list[i].Equals(newVersion))
                        {
                            try
                            {
                                string _path = DirTool.Combine(R.Paths.Root, list[i]);
                                if (Directory.Exists(_path))
                                {
                                    Directory.Delete(_path, true);
                                }
                            }
                            catch { }
                        }
                    }
                    #endregion
                    #region 重新清点历史主程序版本删除情况
                    StringBuilder newHistory = new StringBuilder();
                    foreach (var l in list)
                    {
                        if (!StringTool.IsNullOrWhiteSpace(l))
                        {
                            try
                            {
                                string _path = DirTool.Combine(R.Paths.Root, l);
                                if (Directory.Exists(_path))
                                {
                                    newHistory.Append($"|{l}|");
                                }
                            }
                            catch { }
                        }
                    }
                    #endregion
                    IniTool.Set(R.Files.Settings, "Version", "JustMetClient-History", newHistory.ToString());
                }
            }
        }
    }
}
